package upm.pb4agent.team5.custom;

import jade.core.AID;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import upm.pb4agent.ontology.SubscribeReferee;
import upm.pb4agent.team5.BaseAgent;
import upm.pb4agent.team5.common.Referee;

public class BRequestRefereeSubscription extends SimpleBehaviour {
	private static final long serialVersionUID = -3039951466459153875L;
	private static final int WAIT_PER_SEARCH = 5000; // Milliseconds
	
	private BaseAgent agent = null;
	private boolean done = false;

	public BRequestRefereeSubscription(BaseAgent agent) {
		this.agent = agent;
	}
	
	public void action() {   
		try {
			AID aid = agent.findAID(Referee.DF_NAME);

			// Get first occurrence
			if (aid != null) {
				// Sending request
				System.out.println(agent.getLocalName() + ": Subscribe message is sent to " + Referee.DF_NAME);		
				agent.send(new SubscribeReferee(), aid, ACLMessage.SUBSCRIBE);
				
				// Getting response
				ACLMessage msg = agent.blockingReceive(getTemplate());

				if (msg.getPerformative() == ACLMessage.AGREE) 
					System.out.println(agent.getLocalName() + ": Subscribed on " + Referee.DF_NAME);
				else  		
					System.out.println(agent.getLocalName() + ": Subscription failed on " + Referee.DF_NAME);
				
				// Setting done flag for finish
				done = true;
			}
			
			agent.doWait(WAIT_PER_SEARCH);
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}

	public boolean done() {
		return done;
	}
	
	private MessageTemplate getTemplate() {
		return MessageTemplate.MatchProtocol(SubscribeReferee.class.getSimpleName());
	}
	
}
